package com.cqndt.disaster.device.parsing;

import com.cqndt.disaster.device.common.util.GetRequestJsonUtils;
import com.cqndt.disaster.device.common.util.IdUtil;
import com.cqndt.disaster.device.dao.DataCmccMapper;
import com.cqndt.disaster.device.vo.Data;
import com.google.gson.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 中国移动onenet数据接入控制器
 */
@RestController
@Slf4j
public class DataCmccAccess {

    @Autowired
    private DataCmccMapper dataMappper;
    @Autowired
    private Gson gson;

    /**
     * 数据接入(存入消息队列)
     *
     * @return
     */
    @PostMapping("/cmcc")
    @ResponseStatus(HttpStatus.OK)
    public void access(HttpServletRequest request) {
        String requestJsonString = null;
        try {
            requestJsonString = GetRequestJsonUtils.getRequestJsonString(request);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(requestJsonString);
        JsonObject jsonObject = new JsonParser().parse(requestJsonString).getAsJsonObject();
        if ((!jsonObject.getAsJsonObject("msg").has("ds_id")) || "".equals(jsonObject.getAsJsonObject("msg").get("ds_id").getAsString())) {
            return;
        }
        Data data = gson.fromJson(jsonObject.get("msg"), Data.class);
        data.setId(IdUtil.getIncreaseIdByNanoTime());
        dataMappper.save(data);
    }

    /**
     * 用于第一次配置onenet，校验接收数据接口
     * 只需要返回参数中msg即可通过验证
     *
     * @param nonce
     * @param msg
     * @param signature
     * @return
     */
    @GetMapping("/cmcc")
    public String testToken(String nonce, String msg, String signature) {
        return msg;
    }
}
